﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iLangl.Transport.Communication;
using System.IO;
using iLangl.Transport;
using System.Text.RegularExpressions;
using Ionic.Zip;
using System.Collections;

namespace iLangl.Transport.Communication
{
	public class PackagesRobotGet : BaseRobotOperation, IRobotGet
	{
		private static Hashtable filesInQueue;
		public static object mutex = new object();

		String _directoryPath = String.Empty;
		public PackagesRobotGet(IRobot robot, String directoryPath) : base(robot) 
		{
			filesInQueue = new Hashtable();
			_directoryPath = directoryPath;
		}


		#region IRobotGet Members

		public virtual IRobotItem Get()
		{

			string[] files = Directory.GetFiles(_directoryPath);
			string fileToProceed = string.Empty;
			foreach (string filename in files)
			{
				if (filesInQueue[filename] == null)
				{
					
					lock (mutex)
					{
						if (filesInQueue[filename] == null)
						{
							fileToProceed  = filename;
							filesInQueue[filename] = true;
							break;
						}
					}
				}
			}

			if (String.IsNullOrEmpty(fileToProceed))
			{
				return null;
			}


			FileInfo fipackage = new FileInfo(fileToProceed);
			IPackage package = null;
			//Implement check in/check out of files
			try
			{
				package = Facade.Instance.PackageManager.DispatchPackageFromFile(fipackage);

			}
			catch (System.Exception ex)
			{
				MoveTo(fipackage, TransportConfiguration.Instance.CorruptedPackageFolder);
				throw ex;
			}
			finally
			{
				filesInQueue[fileToProceed] = null;
			}

			return package;
		}

		#endregion
	}
}
